package com.xq.shop.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author gaoxiaojin
 */
public class SendEmailUtil {

    public static void senEmail(String to, String code) {
//        // 发件人的电子邮件地址
//        String from = "xjgao02@hotmail.com";
//        // SMTP服务器地址
//        String host = "smtp-mail.outlook.com";
//        // SMTP服务器端口
//        final String port = "587";
//        // 发件人的邮箱用户名
//        final String username = "xjgao02@hotmail.com";
//        // 发件人的邮箱密码
//        final String password = "gxj@092116";
//
//        // 设置系统属性
//        Properties properties = System.getProperties();
//        properties.put("mail.smtp.host", host);
//        properties.put("mail.smtp.port", port);
//        properties.put("mail.smtp.auth", "true");
//        properties.put("mail.smtp.starttls.enable", "true");
        // 发件人的电子邮件地址
        String from = "xingqun174@gmail.com";
        // SMTP服务器地址
        String host = "smtp.gmail.com";
        // SMTP服务器端口
        final String port = "587";
        // 发件人的邮箱用户名
        final String username = "xingqun174@gmail.com";
        // 发件人的邮箱密码
        final String password = "joaoctlemqfnkjxj";

        // 设置系统属性
        Properties properties = System.getProperties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // 获取默认的Session对象
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        try {
            // 创建默认的MimeMessage对象
            MimeMessage message = new MimeMessage(session);
            // 设置From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // 设置To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // 设置Subject: 头部字段
            message.setSubject("Your Verification Code");
            // 设置消息体
            message.setText("Your verification code is: " + code);
            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }

    // 生成6位随机验证码
    public static String generateVerificationCode() {
        int code = (int)(Math.random() * 900000) + 100000;
        return String.valueOf(code);
    }
}
